# -*- coding: utf-8 -*-
#===================================================
# @Time : 2021/3/25 17:29                           
# @Author : weni09                                  
# @File : login_view.py
#===================================================

from .fastapi_admin.schemas import LoginIn
from tortoise import timezone
from datetime import datetime
from fastapi.exceptions import HTTPException,RequestValidationError,FastAPIError,WebSocketRequestValidationError
from tortoise.exceptions import BaseORMException
from .fastapi_admin.shortcuts import get_object_or_404
from .fastapi_admin.factory import app
from starlette.status import HTTP_403_FORBIDDEN
from .token import token


async def last_login(user,login_in: LoginIn):
    """
     update last time for login in ,updating if successfully does't effect to login in.
    :param user:
    :param login_in:
    :return: True
    """
    try:
        time_value = timezone.now()
        if timezone.get_use_tz():
            if timezone.is_naive(time_value):
                time_value = timezone.make_aware(time_value, "UTC")
        time_str = datetime.strftime(time_value,'%Y-%m-%d %H:%M:%S.%f')
        await user.filter(username=login_in.username).update(last_login=time_str)
    except (BaseORMException,RequestValidationError,WebSocketRequestValidationError,FastAPIError):
        pass
    return True


async def login(login_in: LoginIn):
    user_model = app.user_model
    user = await get_object_or_404(user_model, username=login_in.username)
    if not user.is_superuser and not user.is_active:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="User is not Active!")
    success_authenticate = token.authenticate_user(user,login_in)
    if not success_authenticate:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Incorrect Password!")
    await last_login(user,login_in) #更新最后登录时间,始终返回True
    # print(success_authenticate)
    access_token,refresh_token= token.create_access_token(success_authenticate)
    # print(access_token)
    success_authenticate.update(token=access_token,refresh_token=refresh_token)
    return success_authenticate



